from flask import  Blueprint,request,make_response,jsonify
from utils import resful,zlcache
from utils.captcha import Captcha
from exts import alidayu
from .forms import SMSCaptchaForm
from  io import BytesIO
from utils.captcha import Captcha
import qiniu
from tasks import send_sms


bp = Blueprint("common", __name__)

@bp.route("/")
def index():
    return "common page"


@bp.route('/sms_captcha/', methods=["POST"])
def sms_captcha():
    form = SMSCaptchaForm(request.form)
    if form.validate():
        telephone = form.telephone.data
        captcha = Captcha.gene_text(number=4)
        # result = alidayu.send_sms(telephone, captcha)
        # result = True
        # if result:
        #     zlcache.set(telephone, captcha)
        #     print("发送的短信验证码是：%s" %captcha)
        #     return resful.success()
        # else:
        #     return resful.paraserror(message="参数错误")

        send_sms(telephone, captcha)
        return resful.success()

    else:
        return resful.paraserror(message="参数错误")


#OSError: cannot open resource  文件路径错误
@bp.route("/captcha/")
def gene_captcha():
   text, image = Captcha.gene_graph_captcha()
   #在zlcache中设置了过期时间是60s
   zlcache.set(text.lower(),text.lower())
   out = BytesIO()
   image.save(out, "png")
   out.seek(0)
   resp = make_response(out.read())
   resp.content_type = "image/png"
   return resp


@bp.route('/uptoken/')
def uptoken():
    access_key = 'rd2FnLlQ0yD04QwIBLudhlk1xztGapGd1_vMhr5W'
    secret_key = 'BmSLGZ12eJrdIoFjOURtO2oRirmW6utcW-QtoDZR'
    q = qiniu.Auth(access_key,secret_key)
    bucket = 'huadong-zxf'
    token = q.upload_token(bucket)
    return jsonify({'uptoken':token})
